from django.shortcuts import render,HttpResponse,redirect
from django.contrib.auth import authenticate
from django.contrib.auth.models import auth
from .models import *
from django.core.paginator import Paginator
# Create your views here.

def zhu(request):
    if request.method == "GET":
        return render(request, "zhu.html")
    if request.method == "POST":
        uname = request.POST.get("uname")
        upwd = request.POST.get("upwd")
        aupwd = request.POST.get("aupwd")
        if upwd != aupwd:
            return HttpResponse("密码不一致")
        date = U_user.objects.all()
        for i in date:
            if i.uname == uname:
                return HttpResponse("用户已经注册")
        U_user.objects.create_user(uname = uname, upwd=upwd)
        return redirect('loginn')

def loginn(request):
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        uname = request.POST.get('uname')
        upwd = request.POST.get('upwd')
        role=request.POST.get('role')
        user = auth.authenticate(uname=uname, upwd=upwd,role=role)
        if user is not None:
            auth.login(request, user)
        elif role=='1':
            return redirect('stu_add')
        elif role=='2':
            return redirect('t_index')
        else:
            return HttpResponse('账号或密码错误')

# checkbox
def t_index(request):
    list = M_jia.objects.all()
    stu=T_type.objects.all()
    paginator = Paginator(list, 2)
    x = request.GET.get("page", '1')
    try:
        x = int(x)
        if x < 0:
            x = 1
    except Exception as e:
        x = 1
    pagex = paginator.get_page(x)
    return render(request, 't_index.html', {"pagex": pagex, 'hasnext': pagex.has_next(),"stu":stu})

def stu_add(request):
    if request.method == "GET":
        stu=T_type.objects.all()
        return render(request, 'stu_add.html',{"stu":stu})
    if request.method == "POST":
        stu_name = request.POST.get("stu_name", "")
        context = request.POST.get("context", "")
        createtime = request.POST.get("createtime", "")
        tid=request.POST.get('tid')
        stu = M_jia(stu_name=stu_name, createtime=createtime, context=context,tid_id=tid)
        stu.save()
        return HttpResponse("添加成功")
